﻿using System;
using System.Linq;
using ApiScanner.Core;

namespace ApiScannerShell.ViewModels
{
    public sealed class TestConfigurationElementCollectionViewModelCollection: ViewModelCollection<IViewModel<TestConfigurationElement>, TestConfigurationElement>
    {
        public TestConfigurationElementCollectionViewModelCollection(TestConfigurationElementCollection tests): base(tests)
        {
            AddValidationRule(() => !this.Any() ? "At lease one test must be specified." : null);
        }

        public void Add(TestConfigurationElement element)
        {
            AddItem(CreateViewModel(element));
        }

        protected override IViewModel<TestConfigurationElement> CreateViewModel(TestConfigurationElement model)
        {
            var exchangeStoreScanner = model as ExchangeStoreScannerTestConfigurationElement;
            var fileScanner = model as FileSystemScannerTestConfigurationElement;
            var smtpScanner = model as SmtpServerEventScannerTestConfigurationElement;

            if (exchangeStoreScanner != null)
            {
                return new ExchangeStoreScannerTestConfigurationElementViewModel(exchangeStoreScanner, RemoveItem);
            }
            if (fileScanner != null)
            {
                return new FileSystemScannerTestConfigurationElementViewModel(fileScanner, RemoveItem);
            }
            if (smtpScanner != null)
            {
                return new SmtpServerEventScannerTestConfigurationElementViewModelConfigurationElement(smtpScanner, RemoveItem);
            }

            throw new NotSupportedException(string.Format("The model type {0} is not supported.",
                                                          model.GetType().FullName));
        }

        public void AddAndConfigure(TestConfigurationElement testConfigurationElement)
        {
            var viewModel = CreateViewModel(testConfigurationElement);
            var dialog = new EditTestConfigurationView(viewModel);
            if (dialog.ShowDialog().GetValueOrDefault())
            {
                AddItem(viewModel);
            }
        }
    }
}